package org.jypj.dev.controller;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.jypj.dev.dao.ILoginInfoDao;
import org.jypj.dev.dao.IRoadDao;
import org.jypj.dev.dao.IUserScoreVoDao;
import org.jypj.dev.model.UserScore;
import org.jypj.dev.util.*;
import org.jypj.dev.vo.CountVo;
import org.jypj.dev.vo.TodayScore;
import org.jypj.dev.vo.UserScoreVo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

/**
 * 统计控制器
 *
 * @author ChenYu
 */
@RequestMapping(value = "countDayController")
@Controller
public class CountDayController {

    @Resource
    private IUserScoreVoDao userScoreVoDao;

    @Resource
    private IRoadDao roadDao;

    @Resource
    private ILoginInfoDao loginInfoDao;


    /**
     * 跳转到日常分析总结页面
     *
     * @return
     */
    @RequestMapping(value = "toCountDayAnalyze.action")
    public String toCountDayAnalyze(HttpServletRequest request) {
        String todayString = DateUtils.getYestodayString("yyyy-MM-dd");
        request.setAttribute("today", todayString);
        return "back/count/count_day_analyze";
    }

    /**
     * 跳转到日常评分统计页面
     *
     * @return
     */
    @RequestMapping(value = "toCountUserScoreList.action")
    public String toCountUserScoreList(HttpServletRequest request) {
        String todayString = DateUtils.getYestodayString("yyyy-MM-dd");
        request.setAttribute("today", todayString);
        return "back/count/count_day_user_score";
    }

    /**
     * 查询所有用户工序
     *
     * @param startDate
     * @return
     */
    @RequestMapping("selectAllUserTrainScore.action")
    @ResponseBody
    public Map<String, Object> selectAllUserTrainScore(String startDate, String searchKey) {
        Map<String, Object> dataMap = new HashMap<>();
        Map<String, Object> queryMap = new HashMap<>();
        int code = 0;
        try {
            queryMap.put("planTime", startDate);
            if (StringUtil.isNotEmpty(searchKey)) {
                queryMap.put("searchKey", searchKey);
            }
            List<UserScoreVo> userScoreVos = userScoreVoDao.selectAllByMap(queryMap);
            dataMap.put("datas", userScoreVos);
        } catch (Exception e) {
            e.printStackTrace();
            code = -1;
        }
        dataMap.put("code", code);
        return dataMap;
    }

    /**
     * 查询分数段人数
     *
     * @return
     */
    @RequestMapping(value = "selectTodayScore.action")
    @ResponseBody
    public Map<String, Object> selectTodayScore(String startDate, HttpServletRequest request) {
        Map<String, Object> dataMap = new HashMap<>();
        Map<String, Object> queryMap = new HashMap<>();
        int code = 0;
        try {
            queryMap.put("planTime", startDate);
            TodayScore ts = new TodayScore();
            ts.setStartDate(startDate);
            int roadNum = roadDao.selectRoadNum();
            int userNum = 0;
            UserScore us1 = userScoreVoDao.selectMaxScoreUser(queryMap);
            UserScore us2 = userScoreVoDao.selectMinScoreUser(queryMap);
            List<CountVo> countVos = userScoreVoDao.selectScoreSpan(queryMap);
            UserScoreUtil.getUserNumAndSetScoreSpan(countVos, ts);
            if (us1 != null) {
                ts.setMaxScore(us1.getScore());
                ts.setMaxScoreUser(us1.getUserName());
            } else {
                ts.setMaxScoreUser("无");
            }
            if (us2 != null) {
                ts.setMinScore(us2.getScore());
                ts.setMinScoreUser(us2.getUserName());
            } else {
                ts.setMinScoreUser("无");
            }
            ts.setRoadNum(roadNum);
            dataMap.put("data", ts);
            request.getSession().setAttribute("countData", ts);
        } catch (Exception e) {
            e.printStackTrace();
            code = -1;
        }
        dataMap.put("code", code);
        return dataMap;
    }

    /**
     * 导出word文档
     *
     * @param startDate
     */
    @RequestMapping(value = "exportWord.action")
    public void exportWord(String startDate, HttpSession session, HttpServletResponse response) {
        Map<String, Object> dataMap = new HashMap<>();
        TodayScore attribute = (TodayScore) session.getAttribute("countData");
        dataMap.put("data", attribute);
        String ftlPath = session.getServletContext().getRealPath("/") + "static/ftl";
        String ftlName = "countDay.ftl";
        String filePath = PropertyUtil.getProperties("file_path") + "/countDay";
        String fileName = startDate + "随车机械师作业情况分析.doc";
        try {
            WordUtil.createWord(dataMap, ftlPath, ftlName, filePath, fileName);
            WordUtil.outputWord(response, fileName, filePath);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 导出所有用户分数excel
     *
     * @param startDate
     */
    @RequestMapping(value = "exportExcelAllUserScore.action")
    public void exportExcelAllUserScore(String startDate, HttpSession session, HttpServletResponse response) {
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("planTime", startDate);
        List<UserScoreVo> userScoreVos = userScoreVoDao.selectAllByMap(queryMap);
        if (userScoreVos != null && userScoreVos.size() > 0) {
            exportExcel(userScoreVos, startDate, session, response);
        }
    }

    /**
     * 导出excel
     *
     * @param userScoreVos
     * @param startDate
     * @param session
     * @param response
     */
    public void exportExcel(List<UserScoreVo> userScoreVos, String startDate, HttpSession session,
                            HttpServletResponse response) {

        WritableWorkbook workbook_temp = null;// Excel数据组装
        String usersTempPath = session.getServletContext().getRealPath("/static/excelModel/") + File.separator
                + "countDayScore_temp.xls";
        String userPath = session.getServletContext().getRealPath("/static/excelModel/") + File.separator
                + "countDayScore.xls";
        Workbook workbook = null; // 工作表
        try {
            workbook = Workbook.getWorkbook(new File(userPath)); // 创建一张工作表从实体路径下
            workbook_temp = Workbook.createWorkbook(new File(usersTempPath), workbook); // 拷贝一份模板
            WritableSheet sheet = workbook_temp.getSheet(0);
            sheet.addCell(new Label(0, 0, startDate + "随车机械师总得分统计表"));
            for (int i = 0; i < userScoreVos.size(); i++) {
                UserScoreVo userScoreVo = userScoreVos.get(i);
                sheet.addCell(new Label(0, 3 + i, i + 1 + ""));
                sheet.addCell(new Label(1, 3 + i, userScoreVo.getUserNum()));
                sheet.addCell(new Label(2, 3 + i, userScoreVo.getUserName()));
                sheet.addCell(new Label(3, 3 + i, userScoreVo.getRoadName()));
                sheet.addCell(new Label(4, 3 + i, userScoreVo.getTrainCodeScore()));
                sheet.addCell(new Label(5, 3 + i, userScoreVo.getSysScore() + "分"));
                sheet.addCell(new Label(6, 3 + i, userScoreVo.getFinalScore() + "分"));
                sheet.addCell(new Label(6, 3 + i,
                        StringUtil.isNotEmpty(userScoreVo.getModUser()) ? userScoreVo.getModUser() : "-"));
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            // 关闭Excel工作薄对象
            if (workbook_temp != null) {
                try {
                    workbook_temp.write();
                    workbook_temp.close();
                    ExcelHelper.outputExcel(response, startDate, usersTempPath);
                    new File(usersTempPath).delete();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            if (workbook != null) {
                workbook.close();
            }
        }

    }

}
